/**
 * Created by liujie on 2017/10/6.
 * 监控管理js
 */
var watchCars = [];
var watchCarIds = [];
var isClickingCarData = null;
var speed = 600;
var _click_num = 0;
var markItems = {};
var goableOnline = "";
var TreeApi = null;
var refZtreeInterval = null;
var refZtreeStatusFn = null;
var checkedNodeObjs = {};
;(function ($,window,undefined) {
    function MonitorView() {
        this.queryTreeData_url = "/monitor/queryTreeData";
        this.queryTreeNodeInfo = "/monitor/queryTreeNodeInfo";
        this.queryCarByStatus_url = "/monitor/queryCarStatus";
        this.queryDevice_url = "/monitor/queryDeviceInfo";
        this.queryCarCount_url = "/monitor/listByCountCar";
        this.$leftTreeArrow = $("#left-tree-arrow");
        this.$leftTree = $("#left-tree");
        this.$bottomArrow = $("#bottom-arrow");
        this.$treeview =$("#treeview");
        this.$searchIcon =$("#search-icon");
        this.$headTab = $("#head-Tab");
        this.$bottomBoxArrow = $("#bottom-box-arrow");
        this.$bottomBox = $("#bottom-box");
        this.$bottomTopArrow = $("#bottom-top-arrow");
        this.myMap = null;
        this.carInfoData = [];
        this.carInfoTable=null;
        this.carInfoTree = null;
        this.oldCarInfoIds = [];

    }
    MonitorView.prototype = {
        initBindEvent:function () {
            var _this = this;
            this.$leftTreeArrow.off("click").on("click",function () {
                $(this).fadeOut(300);
                $("#left-box-id").css({"display":"block"}).animate({
                    "width":"240px"
                },speed);
                $("#mymap-box").animate({
                    "marginLeft":"240px"
                },speed);
                $(".row-box-col").animate({
                    "width":"41%"
                },speed);
                // _this.$leftTree.fadeIn(300,function () {
                //     _this.$treeview.show();
                // });
            });
            this.$bottomArrow.off("click").on("click",function () {

               // _this.$treeview.hide();
                $("#left-box-id").animate({
                    "width":"0px"
                },speed,function () {
                    $("#left-box-id").css({"display":"none"});
                    _this.$leftTreeArrow.show();
                });
                $("#mymap-box").animate({
                    "marginLeft":"0px"
                },speed);
                $(".row-box-col").animate({
                    "width":"50%"
                },speed);
                // _this.$leftTree.fadeOut(300);
                // _this.$leftTreeArrow.fadeIn(300)
            });
            this.$searchIcon.off("click").on("click",function () {
                //_this.carInfoTree.checkNode(data);
                _this.carInfoTree.reload("/monitor/refZTree",{
                    baseCarNo:$("#deviceInfo").val(),
                    online:goableOnline,
                },setOldCheckCar)
            });
            this.$headTab.off("click").on("click","li",function () {
                // var _tabCode = $(this).attr("tabCode");
                // _this._searchByTabCode(_tabCode);
            });
            this.$bottomBoxArrow.off("click").on("click",function () {
                $(this).hide();
                $("#bottom-box").css({"display":"block"});
                $("#bottom-box").animate({
                    "height":"200px"
                },speed);
            });
            this.$bottomTopArrow.off("click").on("click",function () {
                $("#bottom-box").animate({
                    "height":"0px"
                },speed,function () {
                    $("#bottom-box").css({"display":"none"});
                    _this.$bottomBoxArrow.show();
                });
                // _this.$bottomBox.slideUp(600,function () {
                //     _this.$bottomBoxArrow.fadeIn(300);
                // });
            });
            if(pointCarId){
                _this.getCarInfo({id:pointCarId},true);
            }
        },
        initTree:function () {
            var _queryTreeData_url = "/monitor/querySessionData";
            var _this = this;
            TreeApi = this.carInfoTree = new BootstrapTree(this.$treeview,{
                url:_queryTreeData_url,
                emptyIcon:"glyphicon glyphicon-menu-left",
                onNodeSelected:function (data) {
                    //_this.getCarInfo(data)
                    //_this.carInfoTree.checkNode(data.nodeId);
                },
                onNodeUnselected:function (data) {
                    //_this.removeCarMarker(data);
                    //_this.carInfoTree.unCheckNode(data.nodeId);
                },
                onNodeChecked:function (data) {
                    _this.getCarInfo(data)
                },
                onNodeUnchecked:function (data) {
                    _this.removeCarMarker(data);
                }
            });
            this.carInfoTree.init(setPointCar);

            function setPointCar(data) {
                if(data){
                    var _node_id = $("#treeview").find("li[data-id='"+pointCarId+"']").attr("data-nodeid");
                    $("#treeview").treeview('checkNode', [parseInt(_node_id), { silent: true }]);
                }
            }
        },
        initMap:function () {
            this.myMap = new MapUtils("mymap");
            this.myMap.init();
        },
        initCarInfoTable:function () {
            var _this = this;
           this.carInfoTable = new BootstrapTable($('#carInfoTable'),{
                data:[],
                sidePagination: "client",
                pagination:false,
               singleSelect:false,
               height:130,
               onClickRow:function (row) {
                   isClickingCarData = row;
                    var result = $.ArrayUtils.find(_this.oldCarInfoIds,function (item) {
                        return  item == row.id;
                    });
                   if(!result){
                       _this.oldCarInfoIds.push(row.id);
                       _this.getCarInfo(row,true);
                   }else{
                       // var _index = $.ArrayUtils.findIndex(_this.oldCarInfoIds,function (item) {
                       //     return  item == row.id;
                       // });
                       // if(_index >-1){
                       //     _this.oldCarInfoIds.splice(_index,1);
                       // }
                       // _this.myMap.removeMarkers(row.id);
                   }
               },
               onUncheck:function (row) {
                   var _index = $.ArrayUtils.findIndex(_this.oldCarInfoIds,function (item) {
                       return  item == row.id;
                   });
                   if(_index >-1){
                       _this.oldCarInfoIds.splice(_index,1);
                   }
                   _this.myMap.removeMarkers(row.id);
               },
               columns: [{
                   checkbox: true
               },{
                    field:"id",
                   title:"关注",
                   formatter:function (value,data,index) {
                       if(data.iswatch === true){
                           return "<a style='color:#0ae;cursor: pointer' id='"+value+"' class='watch-box' iswatch='true'><img style='width: 22px;height:22px' src='images/page1/watch.png'></a>"
                       }else{
                           return "<a style='color:#0ae;cursor: pointer' id='"+value+"' class='watch-box' iswatch='false'><img style='width: 22px;height:22px' src='images/page3/u1289.png'></a>"
                       }
                   }
               },{
                   field:"id",
                   title:"图标",
                   formatter:function (value,data,index) {
                       var _treeData = data;
                       var r = "";
                       if(_treeData["warningTypes"] == 0){
                           r = "<img src='images/page3/round-black.png' style='width: 20px;height: 20px'>";
                       }else if(_treeData["warningTypes"] == 1){
                           r = "<img src='images/page3/round-blue.png' style='width:20px;height:20px'>";
                       }
                       else if(_treeData["warningTypes"] == 2){
                           r = "<img src='images/page3/round-red.png' style='width: 20px;height: 20px'>";
                       }
                       else if(_treeData["warningTypes"] == 3){
                           r = "<img src='images/page3/round-red.png' style='width: 20px;height: 20px'>";
                       }
                       else if(_treeData["warningTypes"] == 5){
                           r = "<img src='images/page3/round-red.png' style='width: 20px;height: 20px'>";
                       }
                       return r;
                   }
               },
                   {
                   field: 'baseCarNo',
                   title: '车牌号'
               }, {
                   field: 'terminal',
                   title: '设备编号'
               },
               //     {
               //     field:"carType",
               //     title:"设备类型"
               // },
                   {
                   field: 'gpsDate',
                   title: '定位时间'
               } ,
                   /*{
                       field: 'onlinetime',
                       title: '停车地点',
                        formatter:function (data) {
                            return "";
                        }
                   }, {
                       field: 'oneHigh',
                       title: '停车时长',
                       formatter:function (value,e,index) {
                           var gpsPowerStatus = e.gpsPowerStatus;
                           var acc = e.accFlag;
                           var oneHigh = e.oneHigh;
                           var sc=Math.floor(oneHigh/60) + "小时" + Math.floor(oneHigh%60) + "分" ;
                           var str=""
                           if(gpsPowerStatus == 1){
                               str="主电正常, "
                           }else{
                               str="主电异常, "
                           }
                           if (acc == 1) {
                               str = str+"点火, "
                           }else{
                               str = str+"熄火, "
                           }
                           if(oneHigh){
                               str=str+" 时长: "+sc
                           }else{
                               str=str+" 时长: 0 分钟"
                           }
                           return str
                       }
                   },*/


                   {
                   field: 'onlinetime',
                   title: '通信时间'
               }, {
                   field: 'deptName',
                   title: '所属用户'
               }, {
                   field: 'gps',
                   title: '定位状态',
                   formatter:function (value,row,index) {
                       var e = row;
                       //e是得到的json数组中的一个item ，可以用于控制标签的属性。
                       var gpsDate = e.gpsDate;
                       var onlinetime = e.onlinetime;
                       var result = "是";
                       if(gpsDate && onlinetime){
                           var totalMilliseconds = Math.abs(Date.parse(new Date(gpsDate)) - Date.parse(new Date(onlinetime)));
                           var totalMinutes=parseInt(totalMilliseconds / 1000 / 60);
                           if(totalMinutes>2){
                               result="否"
                           }
                       }else{
                           result="否"
                       }
                       return result
                   }
               },
                   {
                       field: 'addressDetail',
                       title: '位置'
                   },
                   /*{
                   field: 'status',
                   title: '激活状态',
                   formatter:function (value,row,index) {
                       var e = row;
                       //e是得到的json数组中的一个item ，可以用于控制标签的属性。
                       var gpsPowerStatus = e.gpsPowerStatus;
                       var acc = e.accFlag;
                       var oneHigh = e.oneHigh;
                       var sc=Math.floor(oneHigh/60) + "小时" + Math.floor(oneHigh%60) + "分" ;
                       var str=""
                       if(gpsPowerStatus == 1){
                           str="主电正常, "
                       }else{
                           str="主电异常, "
                       }
                       if (acc == 1) {
                           str = str+"点火, "
                       }else{
                           str = str+"熄火, "
                       }
                       if(oneHigh){
                           str=str+" 时长: "+sc
                       }else{
                           str=str+" 时长: 0 分钟"
                       }
                       return str
                   }
               },*/
                   {
                   field: 'speed',
                   title: '速度'
               }, {
                   field: 'baojing',
                   title: '方向',
                   formatter:function (value,row,index) {
                       var e = row;
                       //e是得到的json数组中的一个item ，可以用于控制标签的属性。
                       var driection = e.driection;
                       if(driection){
                           return $.mapMethod.queryDriection(driection);
                       }else{
                           return "北"
                       }
                   }
               },{
                   field: 'daydis',
                   title: '日里程',
               },{
                   field: 'totalDis',
                   title: '总里程',
               },
                   {
                       field: 'monthDis',
                       title: '温度',
                       formatter:function (value,row,index) {
                            return ""
                       }
                   },
                   // {
                   //     field: 'monthDis',
                   //     title: '当日油耗',
                   //     formatter:function (value,row,index) {
                   //         return ""
                   //     }
                   // },
                   // {
                   //     field: 'monthDis',
                   //     title: '总油耗',
                   //     formatter:function (value,row,index) {
                   //         return ""
                   //     }
                   // }
               //     {
               //     field: 'Level',
               //     title: '操作'
               // }
               ]
                // columns: [{
                //     checkbox: true
                // }, {
                //     field: 'name',
                //     title: '关注'
                // }, {
                //     field: 'deptName',
                //     title: '设备名称'
                // }, {
                //     field: 'carType',
                //     title: '设备类型'
                // } , {
                //     field: 'baseCarNo',
                //     title: '设备ID'
                // }, {
                //     field: 'sim',
                //     title: 'SIM卡号'
                // }, {
                //     field: 'stopDate',
                //     title: '停车时间'
                // }, {
                //     field: 'stopLocation',
                //     title: '停车地点'
                // }, {
                //     field: 'stopTime',
                //     title: '停车时长'
                // }, {
                //     field: 'baojing',
                //     title: '报警'
                // }, {
                //     field: 'Level',
                //     title: '操作'
                // }]

            });
            this.carInfoTable.init();
        },
        _doSearchByDevice:function () {

        },
        _searchByTabCode:function (tabCode) {
            var _this = this;
            $.ajax({
                url:_this.queryCarByStatus_url,
                data:{"tabCode":tabCode},
                type:"GET",
                dataType:"JSON"
            }).done(function (result) {
                if(result){
                    for(var i=0;i<result.length;i++){
                        _this.myMap.addMarkIcon(result[i]);
                    }
                }
            }).fail(function (error) {
            })
        },
        getLocalListCarCount:function () {
            var _this = this;
            $.ajax({
                url:"/monitor/listSessionCountCar",
                type:"POST",
                dataType:"JSON"
            }).done(function (result) {
                if(result.isSuccess == true){
                    window.offlineStr =result.offlineStr;
                    window.onlineStr =result.onlineStr;
                    $(".allCar").text(result.data.totalNum);
                    $(".onCar").text(result.data.onlineNum);
                    $(".upCar").text(result.data.offlineNum);
                    $(".runNum").text(result.data.speedNum);
                    $(".stopNum").text(result.data.stopNum);
                    $(".speedRate").text(result.data.rate);

                    var $rootli = $("#treeview").find("li[data-id='1']");
                    if($rootli && $rootli.length){
                        var $root = $rootli.find("span.carname");
                        var _text = $root.text();
                        var oldTextStart = _text.substring(0,_text.indexOf("(")+1);
                        var oldEnd = _text.substring(_text.indexOf("/"),_text.length);
                        var line_num = _text.substring(_text.indexOf("(")+1,_text.indexOf("/"));
                        var __count = $($(".onCar")[0]).text();
                        var __total = $($(".allCar")[0]).text();
                        $("#treeview").find("li[data-id='1']").find("span.carname").text(oldTextStart+__count+"/"+__total+")");
                    }

                }
            }).fail(function (error) {
            })
        },
        getListCarCount:function () {
            var _this = this;
            $.ajax({
                url:_this.queryCarCount_url,
                type:"GET",
                dataType:"JSON"
            }).done(function (result) {
                if(result.isSuccess == true){
                    $(".allCar").text(result.data.totalNum);
                    $(".onCar").text(result.data.onlineNum);
                    $(".upCar").text(result.data.offlineNum);
                    $(".runNum").text(result.data.speedNum);
                    $(".stopNum").text(result.data.stopNum);
                    $(".speedRate").text(result.data.rate);
                }
            }).fail(function (error) {
            })
        },
        getCarInfo:function (data,isTable,isInterval) {
            var _carIds = [];
            if(isInterval){
                // for(var m=0;m<this.oldCarInfoIds.length;m++){
                //     this.myMap.removeMarkers(this.oldCarInfoIds[m]);
                // }
                _carIds = this.oldCarInfoIds;
            }else{
                var _isCar = false;
                //var childrenNodes = this.carInfoTree.getChildrenNodes(data.nodeId);
                if(data.isCar){
                    _isCar = true;
                    _carIds.push(data.id);
                }
                // if(childrenNodes && childrenNodes.length){
                //     _isCar = true;
                //     for(var k=0,
                //             _len = childrenNodes.length;k<_len;k++){
                //         var children = childrenNodes[k];
                //         if(children.isCar){
                //             _carIds.push(children.id);
                //         }
                //     }
                // }
                if(!_isCar && !isTable){
                    return false;
                }
                if(!isTable){
                    for(var j = 0;j<_carIds.length;j++){
                        var _carId = _carIds[j];
                        var result = $.ArrayUtils.find(this.oldCarInfoIds,function (item) {
                            return  item == _carId;
                        });
                        if(!result){
                            this.oldCarInfoIds.push(_carId);
                        }
                    }
                }
                if(isTable){
                    _carIds = data.id;
                    this.oldCarInfoIds.push(_carIds);
                }

            }
            var _this = this;
            $.ajax({
                url:this.queryTreeNodeInfo,
                data:{"carIds":_carIds.toString()},
                type:"POST",
                dataType:"JSON"
            }).done(function (result) {
                if (result.isSuccess == true) {
                    var dataArr = [];
                    var resData = result.data;
                    var isNoHasMark = false;
                    var $myMarkIcons = $("#mymap-box").find(".mymap-box");
                    if(isInterval){
                        $myMarkIcons.removeAttr("isaddmark");
                    }
                    $.each(resData, function (key, value) {
                        if(key < 4){
                            for(var m=0;m<$myMarkIcons.length;m++){
                                var item =$myMarkIcons[m];
                                var _val = $(item).attr("idvalue");
                                var _isAddMark =$(item).attr("isaddmark");
                                if(!_isAddMark){
                                    isNoHasMark = true;
                                    $(item).attr("isaddmark",true);
                                    $(item).find("span.text").text(value.terminal)
                                    var _idValue = "mybox"+_val;
                                    if(markItems[_idValue]){
                                        delete  markItems[_idValue]
                                    }
                                    markItems[_idValue] = {
                                        "carId":value.id,
                                        "domob":$(item)
                                    };
                                    if(_val == "0"){
                                        markItems[_idValue]["mapObject"] =_this.myMap
                                        _this.myMap.clearMarkers();
                                        _this.myMap.addMarkIcon(value);
                                    }else if(_val == "1"){
                                        markItems[_idValue]["mapObject"] =myMap1
                                        myMap1.clearMarkers();
                                        myMap1.addMarkIcon(value);
                                    }else if(_val == "2"){
                                        markItems[_idValue]["mapObject"] =myMap2
                                        myMap2.clearMarkers();
                                        myMap2.addMarkIcon(value);
                                    }else if(_val == "3"){
                                        markItems[_idValue]["mapObject"] =myMap3
                                        myMap3.clearMarkers();
                                        myMap3.addMarkIcon(value);
                                    }
                                    break;
                                }
                            }
                            if(!isNoHasMark){
                                $myMarkIcons.removeAttr("isaddmark");
                                _this.myMap.clearMarkers();
                                _this.myMap.addMarkIcon(value);
                            }
                        }



                        var r = $.ArrayUtils.find(_this.carInfoData,function (item) {
                            return item.id == value.id;
                        });
                        if(!r){
                            //dataArr.push(value);
                        }else if(r){
                            // var _index = $.ArrayUtils.findIndex(_this.carInfoData,function (item) {
                            //     return item.id = value.id
                            // });
                            // if(_index > -1){
                            //     _this.carInfoData[_index] = value;
                            // }
                        }
                        dataArr.push(value);
                    });
                    _this.carInfoData = _this.carInfoData.concat(dataArr);
                    // _this.carInfoTable.load(_this.carInfoData);
                    // for(var j=0,
                    //         _carLen = _this.carInfoData.length;j<_carLen;j++){
                    //     _this.carInfoTable.check(j);
                    // }


                    // for(var j=0,
                    //         _carLen = _carIds.length;j<_carLen;j++){
                    //     var _carId = _carIds[j];
                    //     var _index = $.ArrayUtils.findIndex(_this.carInfoData,function (item) {
                    //         return item.id = _carId
                    //     });
                    //     _this.carInfoTable.check(_index);
                    // }
                }
            }).fail(function (error) {

            })
        },
        removeCarMarker:function (data) {
            var _this = this;
            var _carIds = [];
            var _isCar = false;
            //var childrenNodes = _this.carInfoTree.getChildrenNodes(data.nodeId);
            if(data.isCar){
                _isCar = true;
                _carIds.push(data.id);
            }
            // if(childrenNodes && childrenNodes.length){
            //     _isCar = true;
            //     for(var k=0,
            //             _len = childrenNodes.length;k<_len;k++){
            //         var children = childrenNodes[k];
            //         if(children.isCar){
            //             _carIds.push(children.id);
            //         }
            //     }
            // }
            if(!_isCar){
                return false
            }
            for(var kk=0,_len=_carIds.length;kk<_len;kk++){
                var _carId = _carIds[kk];
                var _index = $.ArrayUtils.findIndex(this.oldCarInfoIds,function (item) {
                    return  item == _carId
                });
                if(_index >-1){
                    this.oldCarInfoIds.splice(_index,1);
                }
                var _carIndex = $.ArrayUtils.findIndex(this.carInfoData,function (item) {
                    return item.id == _carId;
                });
                if(_carIndex >-1){
                    this.carInfoData.splice(_carIndex,1);
                }
                for(var k in markItems){
                    var _item = markItems[k];
                    if(_item["carId"] && _item["carId"] == _carId){
                        _item["mapObject"].clearMarkers();
                        _item["domob"].removeAttr("isaddmark");
                        delete markItems[k];
                    }
                }

                //_this.myMap.removeMarkers(_carId);
            }
             //    this.carInfoTable.load(this.carInfoData);
             // for(var c=0;c<this.carInfoData.length;c++){
             //     this.carInfoTable.check(c);
             // }
        }
    };

    var monitorView = new MonitorView();
    monitorView.getLocalListCarCount();
    monitorView.initTree();
    monitorView.initBindEvent();
    monitorView.initMap();
    monitorView.initCarInfoTable();
    // $.post("/monitor/queryTreeData",{pointCarId:pointCarId?pointCarId:""},function (result) {
    // },"json");
    // $.post("/monitor/queryTreeData",{
    //     online:"1",
    //     pointCarId:pointCarId?pointCarId:""
    // },function (result) {
    // },"json");
    // $.post("/monitor/queryTreeData",{
    //     online:"0",
    //     pointCarId:pointCarId?pointCarId:""
    // },function (result) {
    // },"json");
    refZtreeStatusFn =  function(){
        // $.post("/monitor/refZTree",function (result) {
        // },"json");
        // $.post("/monitor/refZTree",{pointCarId:pointCarId?pointCarId:""},function (result) {
        // },"json");
        // $.post("/monitor/refZTree",{
        //     online:"1",
        //     pointCarId:pointCarId?pointCarId:""
        // },function (result) {
        // },"json");
        // $.post("/monitor/refZTree",{
        //     online:"0",
        //     pointCarId:pointCarId?pointCarId:""
        // },function (result) {
        // },"json");
        // if(monitorView.oldCarInfoIds.length){
        //     isMapPanto=false;
        //     monitorView.getCarInfo(null,null,true);
        // }
        console.log(new Date());
        if(window.treeJsonData.length){
            var middleData = window.treeJsonData;
            for(var i=0,
                    _len=middleData.length;i<_len;i++){
                var _node = middleData[i];
                //var _index = window.offlineStr.indexOf(_node.terminal);
                var _updatedNode = window.updatedTreeCars[_node.base_terminal_id];
                // if(_index !=-1){
                //     var node = window.carTreeJSON[_node.terminal];
                //     // var _onlineName = "-1";
                //     _node["pid"]=node["pid"];
                //     _node["parentId"]=node["parentId"];
                //     if( !_updatedNode || _updatedNode.isOnLine === false){
                //         TreeApi.refreshTreeNode(_node,true)
                //     }
                // }
                var node = window.carTreeJSON[_node.base_terminal_id];
                if(node){
                    // var _onlineName = "-1";
                    _node["id"] = node["id"];
                    _node["pid"]=node["pid"];
                    _node["parentId"]=node["parentId"];
                    _node["uname"] = node["uname"];
                    if(_updatedNode){
                        if(_updatedNode.online != _node.online){
                            refresh(_node)
                        }
                    }else{
                        var __online="0";
                        var __warningType = node["warningType"];
                        if(__warningType == 0){
                            __online="0";
                        }else if(__warningType == 1 || __warningType == 2){
                            __online="1";
                        }else if(__warningType == 3 || __warningType == 5 || __warningType == 8){
                            __online="0";
                        } else{
                            __online="0";
                        }
                        if( _node.online != __online){
                            refresh(_node)
                        }
                    }
                }

            }
        }
        console.log(new Date());

        function refresh(node) {
            if(node.online == 0){
                TreeApi.refreshTreeNode(node,false)
            }else if(node.online == 1){
                TreeApi.refreshTreeNode(node,true)
            }
        }
    };
    setInterval(function () {
        if(monitorView.oldCarInfoIds.length){
            isMapPanto=false;
            monitorView.getCarInfo(null,null,true);
        }
    },60000);
    setInterval(function () {
        monitorView.getListCarCount();
    },300000);
    setInterval(function () {
        $.post("/monitor/refDeptIdsRef",function (result) {
            window.deptsCarIdJson = result;
        },"json");
    },600000);


    // setInterval(function () {
    //     //monitorView.getListCarCount();
    //     if(monitorView.oldCarInfoIds.length){
    //         monitorView.getCarInfo(null,null,true);
    //     }
    // },30000);
    //
    // setInterval(function () {
    //     monitorView.getListCarCount();
    // },300000);


    $("#carInfoDialog").DialogExt({
        title: '车辆基本信息',
        keyboard: true,
        show: false,
        maxHeight:"300",
        scrollY:true,
        showButton:false,
        onSure: function () {
        }
    });
    $("#guanzhu").on("click",function () {
        var _visible = $(this).attr("data-visible");
        if(_visible == "true"){
            $(this).attr("data-visible","false");
            $("#guanzhu-box-content").animate({
                width:"0px",
                height:"0px",
                opacity: "0",
            },300)
        }else{
            $(this).attr("data-visible","true");
            $("#guanzhu-box-content").animate({
                width:"800px",
                height:"35px",
                opacity: "1",
            },300)
        }

    });
    $(document).bind("contextmenu",function(e){
        return false;
    });
    $(document).bind("click",function(e){
        if($("#rightkey-box").is(":visible")){
            $("#rightkey-box").hide();
        }
    });
    $("#treeview").on("mousedown","li",function (e) {
        var _e = e ? e : window.event;
        _e.preventDefault();
        var isCarDom = $(this).find("span.isCar").length ? true : false;
        if(_e.which==3 && isCarDom){
            var _y = _e.pageY;
            _y = $(".monitor-box").scrollTop() + _y -72;
            $("#rightkey-box").show().css({
                "top":_y+"px",
                "left":"200px"
            })
        }
    });
  
    $(".hover-box").hover(function () {
        $("#hover-box-ul").show().stop(true);
        return false
    },function () {
        $("#hover-box-ul").hide().stop(true);
        return false
    });
    $("#left-head-tab").on("click","div",function () {
        var _id = $(this).attr("id");
        var $span =$(this).find("span.text");
        // if($span.hasClass("active")){
        //     return false
        // }
        $("#left-head-tab").find("span.text").removeClass("active");
        $span.addClass("active");
        if(_id == "everyCar"){
            goableOnline="";
            monitorView.carInfoTree.reload("/monitor/querySessionAllData",{},setOldCheckCar);
            // $("#onlineDialog").hide();
            // $("#unonlineDialog").hide();
            // $("#carDetailsDialog").hide();
        }else if(_id == "onlineCar"){
            goableOnline="1";
            monitorView.carInfoTree.reload("/monitor/querySessionOnlineData",{
                online:"1"
            },setOldCheckCar);
            // $("#onlineDialog").show();
            // $("#unonlineDialog").hide();
            // $("#carDetailsDialog").hide();
        }else if(_id == "unOnlineCar"){
            goableOnline="0";
            monitorView.carInfoTree.reload("/monitor/querySessionUnOnlineData",{
                online:"0"
            },setOldCheckCar);
            // $("#unonlineDialog").show();
            // $("#onlineDialog").hide();
            // $("#carDetailsDialog").hide();
        }
    });
    function setOldCheckCar(data) {
        var carInfoDatas = monitorView.carInfoData;
        if(data && carInfoDatas && carInfoDatas.length){
            for(var n=0,
                    _len=carInfoDatas.length;n<_len;n++){
                var _carInfoData = carInfoDatas[n];
                var _node_id = $("#treeview").find("li[data-id='"+_carInfoData.id+"']").attr("data-nodeid");
                $("#treeview").treeview('checkNode', [parseInt(_node_id), { silent: true }]);
            }
        }
    }
    $("#left-head-tab").on("mousedown","div",function (e) {
        var _e = e ? e : window.event;
        _e.preventDefault();
        //var isCarDom = $(this).find("span.isCar").length ? true : false;
        if(_e.which==3){
            var _id = $(this).attr("id");
            //var $span =$(this).find("span.text");
            // if($span.hasClass("active")){
            //     return false
            // }
            //$("#left-head-tab").find("span.text").removeClass("active");
            //$span.addClass("active");
            if(_id == "everyCar"){
                $("#onlineDialog").hide();
                $("#unonlineDialog").hide();
                $("#carDetailsDialog").hide();
            }else if(_id == "onlineCar"){
                $("#onlineDialog").show();
                $("#unonlineDialog").hide();
                $("#carDetailsDialog").hide();
            }else if(_id == "unOnlineCar"){
                $("#unonlineDialog").show();
                $("#onlineDialog").hide();
                $("#carDetailsDialog").hide();
            }
        }
    });
    // $("#onlineCar").on("click",function () {
    //     $("#onlineDialog").show();
    // });
    $("#onlineClose").on("click",function () {
        $("#onlineDialog").hide();
    });
    // $("#unOnlineCar").on("click",function () {
    //     $("#unonlineDialog").show();
    // });
    $("#unOnlineClose").on("click",function () {
        $("#unonlineDialog").hide();
    });

    $("#exportONlineCar").click(function () {
        window.location.href = window.serveraddr+"/carHisExcel/exportCarStateExcel?online=1"
    });
    $("#exportUnONlineCar").click(function () {
        window.location.href = window.serveraddr+"/carHisExcel/exportCarStateExcel?online=0"
    });
    /**
     * 在线列表
     * @type {BootstrapTable}
     */
    var onlineCarInfoTable  = new BootstrapTable($('#onlineCarInfoTable'),{
        url:"/monitor/listByRealOnLineCar",
        pagination:false,
        singleSelect:false,
        columns: [ {
            field: 'baseCarNo',
            title: '车牌号'
        }, {
            field: 'terminal',
            title: '设备编号'
        }, {
            field: 'deptName',
            title: '所属用户'
        },
            {
                field: 'gpsDate',
                title: '当前在线时间'
            },
            {
                field: 'oneHigh',
                title: '离线时间',
                formatter:function (e) {
                    var gpsPowerStatus = e.gpsPowerStatus;
                    var acc = e.accFlag;
                    var oneHigh = e.oneHigh;
                    var sc=Math.floor(oneHigh/60) + "小时" + Math.floor(oneHigh%60) + "分" ;
                    var str=""
                    if(gpsPowerStatus == 1){
                        str="主电正常, "
                    }else{
                        str="主电异常, "
                    }
                    if (acc == 1) {
                        str = str+"点火, "
                    }else{
                        str = str+"熄火, "
                    }
                    if(oneHigh){
                        str=str+" 时长: "+sc
                    }else{
                        str=str+" 时长: 0 分钟"
                    }
                    return str
                }
            },
            {
                field: 'oneHigh',
                title: '在线状态'
            }
        ]
    });
    onlineCarInfoTable.init();
    /**
     * 离线列表
     * @type {BootstrapTable}
     */
    var unOnlineCarInfoTable  = new BootstrapTable($('#unOnlineCarInfoTable'),{
        url:"/monitor/listByRealOutLineCar",
        pagination:false,
        singleSelect:false,
        columns: [ {
            field: 'baseCarNo',
            title: '车牌号'
        }, {
            field: 'terminal',
            title: '设备地址'
        }, {
            field: 'deptName',
            title: '所属用户'
        },
            {
                field: 'gpsDate',
                title: '最后在线时间'
            },
            {
                field: 'oneHigh',
                title: '离线时长',
                formatter:function (e) {
                    var gpsPowerStatus = e.gpsPowerStatus;
                    var acc = e.accFlag;
                    var oneHigh = e.oneHigh;
                    var sc=Math.floor(oneHigh/60) + "小时" + Math.floor(oneHigh%60) + "分" ;
                    var str=""
                    if(gpsPowerStatus == 1){
                        str="主电正常, "
                    }else{
                        str="主电异常, "
                    }
                    if (acc == 1) {
                        str = str+"点火, "
                    }else{
                        str = str+"熄火, "
                    }
                    if(oneHigh){
                        // str=str+" 时长: "+sc
                        str=" 时长: "+sc
                    }else{
                        // str=str+" 时长: 0 分钟"
                        str=" 时长: 0 分钟"
                    }
                    return str
                }
            }
        ]
    });
    unOnlineCarInfoTable.init();
    /**
     * 关注列表
      * @type {BootstrapTable}
     */
    var guanzhuInfoTable  = new BootstrapTable($('#guanzhuInfoTable'),{
        data:[],
        sidePagination: "client",
        pagination:false,
        singleSelect:false,
        columns: [
            {
                field: 'baseCarNo',
                title: '车牌号'
            },
            // {
            //     field: 'deptName',
            //     title: '所属用户'
            // },
            // {
            //     field: 'terminal',
            //     title: '设备名称'
            // },
            {
                field: 'carTypes',
                title: '车辆类型'
            },
            {
                field: 'id',
                title: '设备ID'
            },
            {
                field: 'sim',
                title: 'SIM卡号'
            },
            {
                field: 'accFlag',
                title: '运行状态',
                formatter:function (value,row,index) {
                    var acc = row.accFlag;
                    if (acc == 1) {
                        return "运行"
                    }else{
                        return "停止"
                    }
                }
            } ,
            {
                field: 'gpsDate',
                title: '停车时间'
            } ,
            {
                field: 'addressDetail',
                title: '停车地点'
            }, {
                field: 'oneHigh',
                title: '停车时长',
                formatter:function (value,row,index) {
                    var e = row;
                    var gpsPowerStatus = e.gpsPowerStatus;
                    var acc = e.accFlag;
                    var oneHigh = e.oneHigh;
                    var sc=Math.floor(oneHigh/60) + "小时" + Math.floor(oneHigh%60) + "分" ;
                    var str="";
                    // if(gpsPowerStatus == 1){
                    //     str="主电正常, "
                    // }else{
                    //     str="主电异常, "
                    // }
                    // if (acc == 1) {
                    //     str = str+"点火, "
                    // }else{
                    //     str = str+"熄火, "
                    // }
                    if(oneHigh){
                        str=str+" 时长: "+sc
                    }else{
                        str=str+" 时长: 0 分钟"
                    }
                    return str
                }
            },
            {
                field: 'warningType',
                title: '报警',
                formatter:function (value,row,index) {
                    //e是得到的json数组中的一个item ，可以用于控制标签的属性。
//                    debugger;
                    var e = row;
                    var d = e.warningType;
//                    1-驶入  2-驶出 3-超速 4-路线偏离 5-停车超时报警  6-疲劳驾驶报警 7-凌晨行车报警
                    var result = "";
                    if (d == 1) {
                        result = '驶入报警'
                    } else if (d == 2) {
                        result = '驶出报警'
                    } else if (d == 3) {
                        result = '超速报警'
                    } else if (d == 4) {
                        result = '路线偏离报警'
                    } else if (d == 5) {
                        result = '停车超时报警'
                    } else if (d == 6) {
                        result = '疲劳驾驶报警'
                    } else if (d == 7) {
                        result = '凌晨行车报警'
                    }
                    return result
                }
            },
            {
                field: 'id',
                title: '操作',
                formatter:function (value,row,index) {
                    //e是得到的json数组中的一个item ，可以用于控制标签的属性。
//                    debugger;
//                    accFlag
//                     var e = row;
//                     var d = e.type;
//                     var result = '';
// //                    车牌号颜色[1-4]黄白蓝黑
//                     if (d == 1) {
//                         result = '';
//                     } else if (d == 0) {
//                         result = '<a style="color: #0ae" class="handelWarning" warningDataId = "'+row.id+'">处理报警</a>';
//                     }
//                     return result;
                    return "<a style='color: #0ae;cursor: pointer' class='cancelWatch' rowid='"+row.id+"'>取消关注</a>"
                }
            },
            // {
            //     field: 'onlinetime',
            //     title: '通信时间'
            // },
            // {
            //     field: 'deptName',
            //     title: '所属用户'
            // },
            // {
            //     field: 'gps',
            //     title: '定位',
            //     formatter:function (value,row,index) {
            //         var e = row;
            //         //e是得到的json数组中的一个item ，可以用于控制标签的属性。
            //         var gpsDate = e.gpsDate;
            //         var onlinetime = e.onlinetime;
            //         var result = "是";
            //         if(gpsDate && onlinetime){
            //             var totalMilliseconds = Math.abs(Date.parse(new Date(gpsDate)) - Date.parse(new Date(onlinetime)));
            //             var totalMinutes=parseInt(totalMilliseconds / 1000 / 60);
            //             if(totalMinutes>2){
            //                 result="否"
            //             }
            //         }else{
            //             result="否"
            //         }
            //         return result
            //     }
            // },
            // {
            //     field: 'status',
            //     title: '状态',
            //     formatter:function (value,row,index) {
            //         var e = row;
            //         //e是得到的json数组中的一个item ，可以用于控制标签的属性。
            //         var gpsPowerStatus = e.gpsPowerStatus;
            //         var acc = e.accFlag;
            //         var oneHigh = e.oneHigh;
            //         var sc=Math.floor(oneHigh/60) + "小时" + Math.floor(oneHigh%60) + "分" ;
            //         var str=""
            //         if(gpsPowerStatus == 1){
            //             str="主电正常, "
            //         }else{
            //             str="主电异常, "
            //         }
            //         if (acc == 1) {
            //             str = str+"点火, "
            //         }else{
            //             str = str+"熄火, "
            //         }
            //         if(oneHigh){
            //             str=str+" 时长: "+sc
            //         }else{
            //             str=str+" 时长: 0 分钟"
            //         }
            //         return str
            //     }
            // },
            // {
            //     field: 'speed',
            //     title: '速度'
            // },
            // {
            //     field: 'baojing',
            //     title: '方向',
            //     formatter:function (value,row,index) {
            //         var e = row;
            //         //e是得到的json数组中的一个item ，可以用于控制标签的属性。
            //         var driection = e.driection;
            //         if(driection){
            //             return $.mapMethod.queryDriection(driection);
            //         }else{
            //             return "北"
            //         }
            //     }
            // },
            // {
            //     field: 'daydis',
            //     title: '日里程',
            // },
            // {
            //     field: 'monthDis',
            //     title: '总里程',
            // }
        ]
    });
    guanzhuInfoTable.init();
    var warningInfoTable  = new BootstrapTable($('#warningInfoTable'),{
        url:"/monitor/listByCarWaring",
        pagination:false,
        singleSelect:false,
        columns: [
            {
                field: 'baseCarNo',
                title: '车牌号'
            },
            {
                field: 'deptName',
                title: '所属用户'
            },
            {
                field: 'warningType',
                title: '报警类型',
                formatter:function (value,row,index) {
                    //e是得到的json数组中的一个item ，可以用于控制标签的属性。
//                    debugger;
                    var e = row;
                    var d = e.warningType;
//                    1-驶入  2-驶出 3-超速 4-路线偏离 5-停车超时报警  6-疲劳驾驶报警 7-凌晨行车报警
                    var result = "";
                    if (d == 1) {
                        result = '驶入报警'
                    } else if (d == 2) {
                        result = '驶出报警'
                    } else if (d == 3) {
                        result = '超速报警'
                    } else if (d == 4) {
                        result = '路线偏离报警'
                    } else if (d == 5) {
                        result = '停车超时报警'
                    } else if (d == 6) {
                        result = '疲劳驾驶报警'
                    } else if (d == 7) {
                        result = '凌晨行车报警'
                    }
                    return result
                }
            },
            {
                field: 'waringtime',
                title: '报警时间'
            },
            {
                field: 'status',
                title: '状态',
                formatter:function (value,row,index) {
                    //e是得到的json数组中的一个item ，可以用于控制标签的属性。
//                    debugger;
//                    accFlag
                    var e = row;
                    var d = e.type;
                    // var result = '<a class="btn btn-info btn-rounded" >已处理</a>'<a class="btn btn-warning btn-rounded" >未处理</a>
                    var result = '已处理';
//                    车牌号颜色[1-4]黄白蓝黑
                    if (d == 1) {
                        result = '已处理'
                    } else if (d == 0) {
                        result = '未处理'
                    }
                    return result
                }
            },
            {
                field: 'sim',
                title: '操作',
                formatter:function (value,row,index) {
                    //e是得到的json数组中的一个item ，可以用于控制标签的属性。
//                    debugger;
//                    accFlag
                    var e = row;
                    var d = e.type;
                    var result = '';
//                    车牌号颜色[1-4]黄白蓝黑
                    if (d == 1) {
                        result = '';
                    } else if (d == 0) {
                        result = '<a style="color: #0ae" class="handelWarning" warningDataId = "'+row.id+'">处理报警</a>';
                    }
                    return result;
                }
            }
        ]
    });
    warningInfoTable.init();
    var opInfoTable  = new BootstrapTable($('#opInfoTable'),{
        url:"/monitor/listByCarWaring",
        pagination:false,
        singleSelect:false,
        columns: [
            {
                field: 'baseCarNo',
                title: '车牌号'
            },
            // {
            //     field: 'deptName',
            //     title: '所属用户'
            // },
            // {
            //     field: 'terminal',
            //     title: '报警类型'
            // },
            {
                field: 'gpsDate',
                title: '时间'
            },
            // {
            //     field: 'status',
            //     title: '状态',
            //     formatter:function (value,row,index) {
            //         var e = row;
            //         //e是得到的json数组中的一个item ，可以用于控制标签的属性。
            //         var gpsPowerStatus = e.gpsPowerStatus;
            //         var acc = e.accFlag;
            //         var oneHigh = e.oneHigh;
            //         var sc=Math.floor(oneHigh/60) + "小时" + Math.floor(oneHigh%60) + "分" ;
            //         var str=""
            //         if(gpsPowerStatus == 1){
            //             str="主电正常, "
            //         }else{
            //             str="主电异常, "
            //         }
            //         if (acc == 1) {
            //             str = str+"点火, "
            //         }else{
            //             str = str+"熄火, "
            //         }
            //         if(oneHigh){
            //             str=str+" 时长: "+sc
            //         }else{
            //             str=str+" 时长: 0 分钟"
            //         }
            //         return str
            //     }
            // },
            {
                field: 'sim',
                title: '内容',
                formatter:function (value,row,index) {
                    return "";
                }
            }
        ]
    });
    opInfoTable.init();


    var chaijiInfoTable  = new BootstrapTable($('#chaijiInfoTable'),{
        data:[],
        sidePagination: "client",
        pagination:false,
        singleSelect:false,
        columns: [
            {
                field: 'terminal',
                title: '序号'
            },
            {
                field: 'carTypes',
                title: '用户名称'
            },
            {
                field: 'id',
                title: '技工'
            },
            {
                field: 'sim',
                title: '类型'
            },
            {
                field: 'gpsDate',
                title: '操作时间'
            }
        ]
    });
    chaijiInfoTable.init();


    // $.ajax({
    //     url:"/monitor/updateWarningType",
    //     type:"POST",
    //     data:{"id":1686},
    //     dataType:"JSON"
    // }).done(function (result) {
    //     debugger;
    // });

    $('#warningInfoTable').on("click","a.handelWarning",function () {
        var _warningDataId = $(this).attr("warningDataId");
        $.ajax({
            url:"/monitor/updateWarningType",
            data:{"id":_warningDataId},
            dataType:"JSON"
        }).done(function (result) {
            //debugger;
        })
    });
    $('#guanzhuInfoTable').on("click","a.handelWarning",function () {
        var _warningDataId = $(this).attr("warningDataId");
        $.ajax({
            url:"/monitor/updateWarningType",
            data:{"id":_warningDataId},
            dataType:"JSON"
        }).done(function (result) {
            //debugger;
        })
    });
    $('#guanzhuInfoTable').on("click","a.cancelWatch",function () {
        var _rowId = $(this).attr("rowid");
        var old_index = $.ArrayUtils.findIndex(monitorView.carInfoData,function (item) {
            if(isClickingCarData){
                return  item.id == isClickingCarData.id;
            }
            return false
        });
        var _index = $.ArrayUtils.findIndex(watchCars,function (item) {
            if(isClickingCarData){
                return  item.id == isClickingCarData.id;
            }
            return false
        });
        watchCars.splice(_index,1);
        watchCarIds.splice(_index,1);
        monitorView.carInfoData[old_index]["iswatch"] = false;
        $("#carInfoTable").find("a#"+_rowId).find("img").attr("src","images/page3/u1289.png");
        $("#carInfoTable").find("a#"+_rowId).attr("iswatch","false");
        if(watchCars.length<=0){
            $("#guanzhu-btn").find("span.box-img").css({"opacity":"1"});
            $("#guanzhu-btn").find("span.text").text("关注").css({"color":"#333"});
            $("#guanzhu-num").css({"display":"none"});
            $("#guanzhu-num").find("em").text(0);
        }
        reloadGuanzhuInfoTable();
    });



    $("#carInfoTable").on("click","a.watch-box",function () {
            var _state = $(this).attr("iswatch");
        var old_index = $.ArrayUtils.findIndex(monitorView.carInfoData,function (item) {
            if(isClickingCarData){
                return  item.id == isClickingCarData.id;
            }
            return false
        });
            if(_state == "true"){
                var _index = $.ArrayUtils.findIndex(watchCars,function (item) {
                    if(isClickingCarData){
                        return  item.id == isClickingCarData.id;
                    }
                    return false
                });
                watchCars.splice(_index,1);
                watchCarIds.splice(_index,1);
                monitorView.carInfoData[old_index]["iswatch"] = false;
                $(this).find("img").attr("src","images/page3/u1289.png");
                if(watchCars.length<=0){
                    $("#guanzhu-btn").find("span.box-img").css({"opacity":"1"});
                    $("#guanzhu-btn").find("span.text").text("关注").css({"color":"#333"});
                    $("#guanzhu-num").css({"display":"none"});
                    $("#guanzhu-num").find("em").text(0);
                }
            }else{
                $(this).attr("iswatch","true");
                monitorView.carInfoData[old_index]["iswatch"] = true;
                watchCars.push(isClickingCarData);
                watchCarIds.push(isClickingCarData.id);
                $(this).find("img").attr("src","images/page1/watch.png");
                if(watchCars.length){
                    $("#guanzhu-btn").find("span.box-img").css({"opacity":"0"});
                    $("#guanzhu-btn").find("span.text").text("已关注").css({"color":"#0ae"});
                    $("#guanzhu-num").css({"display":"block"});
                    $("#guanzhu-num").find("em").text(watchCarIds.length);
                }
            }
        reloadGuanzhuInfoTable();
    });
    $("#guanzhu-btn").on("click",function () {
        $("#guanzhuDialog").show();
    });
    $("#guanzhuClose").on("click",function () {
        $("#guanzhuDialog").hide();
    });
    $("#carDetailsDialogClose").on("click",function () {
        $("#carDetailsDialog").hide();
    });
    $("#chaijiDialogClose").on("click",function () {
        $("#chaijiDialog").hide();
    });
    function reloadGuanzhuInfoTable() {
        $.post("/monitor/listByCarIds",{"allCarIds":watchCarIds.toString()},function (result) {
            if(result.isSuccess){
                guanzhuInfoTable.load(result.rows);
            }else{
                guanzhuInfoTable.load([]);
            }
        },"json")
    }

    $("#bottom-header").on("click","div.bottom-header-tab",function () {
        var $this = $(this);
        if($this.hasClass("active")){
            return false
        }
        $("#bottom-header").find("div.bottom-header-tab").removeClass("active");
        $this.addClass("active");
        $("div.bottom-table-box").css({"display":"none"});
        $("div.bottom-table").find("div[tableid='"+$this.attr("tableId")+"']").css({"display":"block"});
    })

})(jQuery,window,undefined);

function _showCarInfo(index,id) {
    $.ajax({
        type: "GET",
        url: "/baseCar/edit",
        cache: false,
        async: true,
        data:{
            id: id
        },
        dataType: "json",
        success: function (data) {
            // $('#carInfoForm').loadDate(data);
            for(var k in data){
                $("#carDetailsInfo").find("[name='"+k+"']").text(data[k] ? data[k] : "");
            }
            $("#carDetailsDialog").show();
            //$("#carInfoDialog").DialogExt("open");
        }
    });
};

function orderonMouseDown(e) {
    var _e = e ? e : window.event;
    _e.preventDefault();
    if(_e.which==3 ){
        var _y = _e.pageY;
        var _x = _e.pageX;
        _y = $(".monitor-box").scrollTop() + _y -72;
        $("#rightkey-box").show().css({
            "top":_y+"px",
            "left":_x+"px"
        })
    }
};

function chaijiFn() {
    $("#chaijiDialog").show();
}
